interface Story {
  id: number;
  name: string;
  title: string | null;
  categoryId: number;
  content: string | null;
  views: number;
  collects: number;
  thumbnail: string;
  createTime: string | null;
}

Page({
  data: {
    stories: [] as Story[],
    current: 1,
    size: 6,
    loading: false,
    hasMore: true,
    refreshing: false
  },

  async onLoad() {
    wx.pageScrollTo({
      scrollTop: 0
    })
    await this.fetchStoryList();
  },

  async onPullDownRefresh() {
    this.setData({
      current: 1,
      hasMore: true,
      refreshing: true
    });
    await this.fetchStoryList();
    wx.stopPullDownRefresh();
  },

  async fetchStoryList() {
    if (this.data.loading || (!this.data.hasMore && !this.data.refreshing)) return;

    this.setData({ loading: true });

    try {
      const response = await new Promise((resolve, reject) => wx.request<{
        code: number;
        message: string;
        data: Story[];
      }>({ 
        url: 'https://fairy.ymdx.cn/v1/fairy/page',
        method: 'POST',
        data: {
          current: this.data.current,
          size: this.data.size
        },
        success: function(res) {
            resolve(res);
        },
        fail: function(err) {
            reject(err);
        }
      }));

      // 检查返回数据
      if (!response.data || response.data.code !== 200) {
        throw new Error(response.data?.msg || '获取故事列表失败');
      }

      const storyList = response.data.data || [];
      const isRefreshing = this.data.refreshing;
      
      this.setData({
        stories: isRefreshing ? storyList : [...this.data.stories, ...storyList],
        current: this.data.current + 1,
        hasMore: storyList.length === this.data.size,
        loading: false,
        refreshing: false
      });
    } catch (error) {
      console.error('获取故事列表失败:', error);
      this.setData({ 
        loading: false,
        refreshing: false
      });
      wx.showToast({
        title: error instanceof Error ? error.message : '获取故事列表失败',
        icon: 'none'
      });
    }
  },
  navigateToStory(e: any) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/story/story?id=${id}`
    });
  },

  async onReachBottom() {
    console.log('触发触底事件');
    if (!this.data.loading && this.data.hasMore) {
      wx.showLoading({
        title: '加载中...'
      });
      await this.fetchStoryList();
      wx.hideLoading();
    }
  }
})